<template>
  <div class="plan_empty">
    <el-divider>基本信息</el-divider>
    <el-form :model="ruleForm" :rules="rules" :inline="true" ref="ruleForm" label-width="160px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title" style="width:217px" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="保养部门" prop="deptId">
        <el-select v-model="ruleForm.deptId" @change="handleChange(ruleForm.deptId)" placeholder="请选择所属部门"
          style="width:100%">
          <el-option v-for="(dict, index) in systemList" :key="index" :label="dict.deptName" :value="dict.deptId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="保养人" prop="upkeepPlanMaintainerList">
        <el-select v-model="ruleForm.upkeepPlanMaintainerList" multiple placeholder="请选择保养人" style="width:100%">
          <el-option v-for="(dict, index) in userList" :key="index" :label="dict.userName" :value="dict.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="循环类型" prop="cycleType">
        <el-select v-model="ruleForm.cycleType" placeholder="请选择循环类型" style="width:100%">
          <el-option v-for="(dict, index) in ['循环保养', '单次保养']" :key="index" :label="dict" :value="index + ''">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生成任务" prop="generateTaskType">
        <el-select v-model="ruleForm.generateTaskType" placeholder="请选择生成任务" style="width:100%">
          <el-option v-for="(dict, index) in ['提前一日', '提前二日', '提前三日', '提前四日', '提前五日']" :key="index" :label="dict"
            :value="index + ''">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="验收人" prop="acceptorId">
        <el-select v-model="ruleForm.acceptorId" placeholder="请选择验收人" style="width:100%">
          <el-option v-for="(dict, index) in acceptorList" :key="index" :label="dict.userName" :value="dict.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="验收方式" prop="acceptanceMode">
        <el-select v-model="ruleForm.acceptanceMode" placeholder="请选择验收方式" style="width:100%">
          <el-option v-for="(dict, index) in acceptanceList" :key="index" :label="dict.dictLabel"
            :value="dict.dictValue">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remake">
        <el-input v-model="ruleForm.remake" style="width:217px" placeholder="请输入备注"></el-input>
      </el-form-item>
      <el-divider>审核信息</el-divider>
      <el-form-item label="审核人" prop="auditVosUser">
        <el-select v-model="ruleForm.auditVosUser" collapse-tags multiple placeholder="请选择审核人" style="width:100%">
          <el-option v-for="dict in acceptorList" :key="dict.index" :label="dict.userName" :value="dict.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="" class="line_style">
        <span v-for="(tag, index) in tagUserList" :key="index">
          <el-tag closable disable-transitions @close="tagChange(tag, index)">
            <span>{{ tag.name }}</span>
          </el-tag>
          <span style="font-size:28px;position: relative;top: 5px;">
            <template v-if="index !== tagUserList.length - 1">
              <i class="el-icon-caret-right"></i>
            </template>
          </span>
        </span>

      </el-form-item>
      <br>
      <el-form-item label="抄送人" prop="auditVosType">
        <el-select v-model="ruleForm.auditVosType" multiple placeholder="请选择抄送人" style="width:100%">
          <el-option v-for="dict in acceptorList" :key="dict.index" :label="dict.userName" :value="dict.userId">
          </el-option>
        </el-select>
      </el-form-item>
      <br>
      <el-divider>保养设备</el-divider>
      <el-form-item label="" prop="">
        <el-button type="primary" plain icon="el-icon-plus" size="medium" @click="handleCreated">添加保养设备</el-button>
      </el-form-item>
      <el-form-item :label="ruleForm.cycleType === '0' ? `循环起算日` : `指定保养日期`" prop="specifyTime"
        style="float: right;margin-right: 6%;">
        <el-date-picker v-model="ruleForm.specifyTime" type="date"
          @change="handleChangeSpecifyTime(ruleForm.specifyTime)" style="width:217px" value-format="yyyy-MM-dd"
          :picker-options="pickerOptions" :placeholder="`请选择${ruleForm.cycleType === '0' ? `循环起算日` : `指定保养日期`}`" />
      </el-form-item>
      <el-table v-loading="loading" :data="noticeList">
        <el-table-column label="序号" align="center" width="50">
          <template slot-scope="scope">
            {{ scope.$index + 1 || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="设备编号" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.equipmentNum || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="设备名称" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.equipmentName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="品牌" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.brand || '-' }}
            <!-- <dict-tag :options="statusFlag" :value="scope.row.status" /> -->
          </template>
        </el-table-column>
        <el-table-column label="规格型号" align="center" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.model || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="供应商" align="center" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.supplierName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" min-width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.unitName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.remark || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="保养标准" align="center" min-width="120">
          <template slot-scope="scope">
            <el-button :disabled="!scope.row.upkeepPlanEquipmentUpkeepTypes" size="small" type="primary"
              icon="el-icon-view" @click="handleSelect(scope.row.upkeepPlanEquipmentUpkeepTypes)">查看标准</el-button>
            <!-- <el-empty v-else :image-size="35"></el-empty> -->
          </template>
        </el-table-column>
        <el-table-column align="center" min-width="220">
          <template slot="header">
            <span style="color:red">*</span> 保养日期

            <!-- {{ ruleForm.cycleType === '0' ? `循环起算日` : `指定保养日期` }} -->
          </template>
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.specifyTime" type="date" style="width:217px" value-format="yyyy-MM-dd"
              :picker-options="pickerOptions" :placeholder="`请选择${ruleForm.cycleType === '0' ? `循环起算日` : `指定保养日期`}`" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button size="small" type="danger" icon="el-icon-delete" @click="handleDelete(scope.$index)">删除
            </el-button>
            <el-button size="small" type="primary" icon="el-icon-thumb" @click="handleCreatedUp(scope.$index)">选择标准
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <br>
    <div align="center">
      <el-button type="primary" size="medium" @click="CommitSubmit">提交</el-button>
      <el-button size="medium" @click="resetQuery">取消</el-button>
    </div>
    <!-- 添加适用设备 -->
    <template v-if="open">
      <AddEquipment @clearOpen="clearOpen" :noticeList="noticeList"></AddEquipment>
    </template>
    <!-- 查看保养标准 -->
    <template v-if="openObject">
      <SelectProject :row="rowArrays"></SelectProject>
    </template>
    <!-- 添加保养标准 -->
    <template v-if="openStand">
      <AddStandard @clearOpenStandard="clearOpenStandard"></AddStandard>
    </template>
  </div>
</template>

<script>
import { getuserlist, getsystemlist } from '@/api/equipment/equipment.js';
import { getdictList, Createdplan } from "@/api/maintenance/insurance/insurance.js"
export default {
  components: {
    AddEquipment: () => import('./form/index.vue'),//添加设备
    SelectProject: () => import('./SelectProject.vue'),
    AddStandard: () => import('./standard/index.vue')//添加标准
  },
  data () {
    return {
      ruleForm: {
        "title": undefined, //标题
        "deptId": undefined, //所属部门ID
        "headId": undefined, //负责人ID
        "cycleType": undefined, //循环类型（0循环保养 1单次保养）
        "generateTaskType": undefined, //生成任务（0提前一日 1提前二日 2提前三日 3提前四日 4提前五日）
        "acceptorId": undefined, //验收人ID
        "acceptanceMode": undefined, //验收方式
        "remake": undefined,//备注
        "eaPartInfoVos": [
          // { "equipmentAccountId": 1 }, //设备台账ID
        ], //保养设备台账集合
        "auditVos": [
          // { "userId": 3, /*用户ID*/ "userType": "0" /*用户类型（0审核人）*/ },

        ],//审核信息（审核人在前，抄送人在后）
        auditVosUser: [],
        auditVosType: [],
        upkeepPlanMaintainerList: []
      },
      pickerOptions: {
        disabledDate (time) {
          // return time.getTime() < Date.now() - 8.64e7; //只能选择今天及今天之后的日期
          return time.getTime() < Date.now() - 8.64e6; //只能选择今天之后的日期，今天的日期也不能选
        }
      },
      open: false,
      openObject: false,
      rowArrays: [],
      noticeList: [],
      loading: false,
      systemList: [],
      userList: [],
      acceptorList: [],
      acceptanceList: [],
      UpkeepIndex: 0,
      openStand: false,
      rules: {
        title: { required: true, message: '必填', trigger: ['blur', 'change'] },
        deptId: { required: true, message: '必填', trigger: ['blur', 'change'] },
        upkeepPlanMaintainerList: { required: true, message: '必填', trigger: ['blur', 'change'] },
        cycleType: { required: true, message: '必填', trigger: ['blur', 'change'] },
        specifyTime: { required: false, message: '必填', trigger: ['blur', 'change'] },
        generateTaskType: { required: true, message: '必填', trigger: ['blur', 'change'] },
        acceptorId: { required: true, message: '必填', trigger: ['blur', 'change'] },
        acceptanceMode: { required: true, message: '必填', trigger: ['blur', 'change'] },
        auditVosUser: { required: true, message: '必填', trigger: ['blur', 'change'] },
        auditVosType: { required: false, message: '必填', trigger: ['blur', 'change'] }
      }
    }
  },
  computed: {
    /**
     * 审核人
     */
    tagUserList () {
      let Arr = []
      this.ruleForm.auditVosUser.map(item => {
        this.acceptorList.map(value => {//用户列表
          if (item === value.userId) {
            Arr.push({
              userId: value.userId,
              name: value.userName
            })
          }
        })
      })
      return Arr
    },
  },
  created () {
    this.getList()
  },
  methods: {
    async getList () {
      let params = await getsystemlist();//部门
      let acceptor = await getuserlist();//验证人
      let acceptance = await getdictList();//验证词典
      this.systemList = params.data
      this.acceptorList = acceptor.data
      this.acceptanceList = acceptance.data
    },
    tagChange (val, index) {
      this.ruleForm.auditVosUser.splice(index, 1)
    },
    /**根据部门查询负责人 */
    async handleChange (Id) {
      let params = {
        deptId: Id
      }
      this.ruleForm.upkeepPlanMaintainerList = []
      // this.systemList.map(item => {
      //   if (item.deptId === Id) {
      //     // this.userList.push({
      //     //   userName: item.leader,
      //     //   userId: item.leaderUserId
      //     // })
      //     this.ruleForm.upkeepPlanMaintainerList.push(item.leaderUserId)
      //   }
      // })
      let user = await getuserlist(params);//负责人
      this.userList = user.data
      // this.ruleForm.headId = ''
    },
    clearOpen (val) {
      this.noticeList = this.removedup([...val, ...this.noticeList], 'equipmentAccountId')
      this.noticeList.map((item) => {
        return {
          ...item,
          specifyTime: undefined,
          upkeepPlanEquipmentUpkeepTypes: []
        }
      })
      this.$message.success('操作成功')
      this.open = false
    },
    /**
     * 子传父
     * @param {选中保养标准集合} List 
     */
    clearOpenStandard (List) {
      this.noticeList[this.UpkeepIndex].upkeepPlanEquipmentUpkeepTypes = List
      this.$message.success('操作成功')
      this.openStand = false
    },
    handleDelete (index) {
      this.noticeList.splice(index, 1)
    },
    handleCreated () {
      this.open = true
    },
    handleSelect (row) {
      this.rowArrays = row
      this.openObject = true
    },
    /**
     * 打开选择保养标准
     */
    handleCreatedUp (index) {
      this.UpkeepIndex = index
      this.openStand = true
    },
    resetQuery () {
      this.$emit('quit')
    },
    /**
     * 指定日期更新触发方法
     * @param {指定日期} tiem 
     */
    handleChangeSpecifyTime (tiem) {
      this.noticeList.forEach(item => {
        item.specifyTime = tiem
      })
    },
    CommitSubmit () {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return
        for (let index = 0; index < this.noticeList.length; index++) {
          const element = this.noticeList[index];
          if (!element.specifyTime) {
            return this.$message.error(this.ruleForm.cycleType === '0' ? `循环起算日不可为空` : `指定保养日期不可为空`)
          }
          if (!element.upkeepPlanEquipmentUpkeepTypes) {
            return this.$message.error('须选择保养标准才可提交')
          }
        }
        // { "userId": 3, /*用户ID*/ "userType": "0" /*用户类型（0审核人）*/ },
        //将审核人与抄送人转换为接口需要的格式转换为接口需要的格式
        this.ruleForm.auditVos = this.ruleForm.auditVosUser.map(item => {//审核人
          return {
            userId: item,
            userType: '0'
          }
        });
        this.ruleForm.auditVosType.map(item => {//抄送人
          this.ruleForm.auditVos.push(
            {
              userId: item,
              userType: '1'
            }
          )
        });
        let params = {
          ...this.ruleForm,
          eaPartInfoVos: this.noticeList.map(item => {
            return {
              equipmentAccountId: item.equipmentAccountId,
              specifyTime: item.specifyTime,
              upkeepPlanEquipmentUpkeepTypes: item.upkeepPlanEquipmentUpkeepTypes.map(item => {
                return {
                  upkeepTypeId: item.upkeepTypeId
                }
              }),
            }
          }),
          upkeepPlanMaintainerList: this.ruleForm.upkeepPlanMaintainerList.map(item => {
            return {
              maintainerId: item
            }
          })
        }
        Createdplan(params).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功')
            this.$emit('quit')
          }
        })
      })
    }
  }

}
</script>

<style lang="scss" scoped>
.line_style ::v-deep .el-form-item__content {
  line-height: 25px;
}

.plan_empty ::v-deep .el-empty {
  padding: 0;
  margin: 0;

  .el-empty__description {
    display: none;
    padding: 0;
    margin: 0;
  }
}
</style>